package com.example.SecondStore.controller;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.api.R;
import com.example.SecondStore.config.AliConfig;
import com.example.SecondStore.entity.Shop;
import com.example.SecondStore.service.ShopService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;

/**
 * 店铺(Shop)表控制层
 *
 * @author GoatCode
 * @since 2024-04-25 09:50:11
 */
@Slf4j
@RestController
@RequestMapping("shop")
public class ShopController extends ApiController {
    /**
     * 服务对象
     */
    @Autowired
    private ShopService shopService;

    @Autowired
    private AliConfig aliConfig;

    @PostMapping("/ossUpload")
    public R upload(@RequestParam("file") MultipartFile multipartFile) throws IOException {


        if (StringUtils.isEmpty(aliConfig.getEndpoint()) || StringUtils.isEmpty(aliConfig.getBucket())) {
            return R.failed("上传不成功");
        }

        // 获取上传的文件名和文件流
        String fileName = multipartFile.getOriginalFilename();
        InputStream fileStream = multipartFile.getInputStream();

        // 创建阿里云 OSS 客户端实例
        OSS ossClient = new OSSClientBuilder().build(aliConfig.getEndpoint(), aliConfig.getId(), aliConfig.getSecret());

        // 执行文件上传操作
        PutObjectRequest putObjectRequest = new PutObjectRequest(aliConfig.getBucket(), fileName, fileStream);
        PutObjectResult putObjectResult = ossClient.putObject(putObjectRequest);

        // 关闭阿里云 OSS 客户端
        ossClient.shutdown();

        // 构建上传成功的文件 URL
        String fileUrl = "https://" + aliConfig.getBucket() + "." + aliConfig.getEndpoint() + "/" + fileName;


        return R.ok(fileUrl);


    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("/shopId{id}")
    public R selectOne(@PathVariable Serializable id) {
        return success(this.shopService.getById(id));
    }

    /**
     * 新增数据
     *
     * @param shop 实体对象
     * @return 新增结果
     */
    @PostMapping
    public R insert(@RequestBody Shop shop) {
        return success(this.shopService.save(shop));
    }
}